<template>
	<swiper class="home-swiper" @change="change" :current="activeIndex">
		<swiper-item v-for="(item, index) in tabLists" class="swiper-item">
			<list-item :list="listCatchData[index]" :load="load[index]" @loadMore="loadMore"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		props: {
			// 上方导航列表数据
			tabLists: {
				type: Array,
				default() {
					return []
				}
			},
			// 当前页面的下标
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				// list: [],
				// 所有页面渲染数据
				listCatchData: [],
				load: {}
			};
		},
		watch: {
			tabLists(newVal) {
				if (newVal.length === 0) return
				this.getList(this.activeIndex)
			}
		},
		// onLoad 只能在页面 created 在组件
		created() {
			// tabLists 还没赋值
			// this.getList(0)
		},
		components: {
			listItem
		},
		methods: {
			// swiper 转换
			change(e) {
				const { current } = e.detail
				this.$emit('change', current)
				// 当不存在数据或者数据不为0时候，才去请求数据
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					this.getList(current)
				}
			},
			// 发送网络请求，获取数据
			async getList(current) {
				if (!this.load[current]) {
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				// console.log(this.tabLists[current].name)
				const { result: res } = await this.$api.callFunction({
					name: 'get_list',
					data: {
						label: this.tabLists[current].name,
						page: this.load[current].page,
						pageSize: 5,
					}
				})
				if (res.data.length === 0) {
					let oldLoad = {}
					oldLoad.loading = 'noMore'
					oldLoad.page = this.load[current].page
					this.$set(this.load, current, oldLoad)
					// 强制熏染页面
					this.$forceUpdate()
					return
				}
				// 懒加载
				// this.listCatchData[current] = res.data 直接赋值不起效果
				// console.log(this.listCatchData)
				// 每次更新新数据时，需要把原来的数据加上
				let oldList = this.listCatchData[current] || []
				oldList.push(...res.data)
				// console.log(oldList)
				// 当数组中的数值发生变化时，因为数组是引用数类型，不会触发更新
				this.$set(this.listCatchData, current, oldList)
			},
			// 上拉加载更多
			loadMore() {
				if (this.load[this.activeIndex].loading === 'noMore') return
				// console.log('-------')
				this.load[this.activeIndex].page++
				this.getList(this.activeIndex)
			}
		}
	}
</script>

<style lang='scss'>
	.home-swiper {
		height: 100%;
		.swiper-item {
			height: 100%;
			overflow: hidden;
			.list-scroll {
				height: 100%;
			}
		}
	}
</style>
